 /**
 * 上海中赢金融信息服务有限公司
 * Copyright (c) 2017-2027 Chinazyjr,Inc.All Rights Reserved.
 */
package com.chinazyjr.framework.web.base;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chinazyjr.framework.common.model.sdto.APIRequest;
import com.chinazyjr.framework.common.model.sdto.APIResult;
import com.chinazyjr.framework.web.exceptions.WebExceptionHandler;
import com.chinazyjr.framework.web.utils.WebUtil;
import com.xiaoleilu.hutool.system.UserInfo;

/**
 * 基础controller <b>@author：</b> mobing <br/>
 * <b>@date：</b> 2016年5月6日 下午3:31:16 <br/>
 * <b>@version: </b> <br/>
 */
public class BaseController {

   private static Logger logger = LoggerFactory.getLogger(BaseController.class);
    /**
     * jsonp回调函数名称
     */
    protected String jsonpCallback = null;

    /**
     * request的map参数
     */
    @SuppressWarnings("rawtypes")
    protected Map paramMap = null;
    /**
     * 返回给ajax的json数据
     */
    protected JSONObject retJson = null;

    /**
     * HttpServletRequest
     */
    private HttpServletRequest request;

    /**
     * HttpServletResponse
     */
    private HttpServletResponse response;

    /**
     * 设置request和response
     * 
     * @param request
     * @param response
     */
    @ModelAttribute
    public void setReqAndRes(HttpServletRequest request, HttpServletResponse response) {
        this.request = request;
        this.response = response;
    }

    /**
     * 获取request对象
     * 
     * @return
     */
    public HttpServletRequest getRequest() {
        return this.request;
    }

    /**
     * 获取response对象
     * 
     * @return
     */
    public HttpServletResponse getResponse() {
        return this.response;
    }

    /**
     * 获取session对象
     * 
     * @return
     */
    public HttpSession getSession() {
        return this.request.getSession(true);
    }

    protected APIRequest apiRequest;
    

	/**
     * controller初始化参数 create by:jackyshang
     */
    public void initParams() {
        //获取apirequest
        apiRequest = getAPIRequestByParamenters();
        // 初始化返回json对象
        this.retJson = new JSONObject();
        //设置登录用户信息
        apiRequest.setClientIP(getIpAddr());
        //获取跨域的jsonpCallback
        this.paramMap = this.getRequestParamters();
        if (null != this.paramMap.get("params")) {
            this.jsonpCallback = (String) this.paramMap.get("jsonpCallback");
        } 
    }
    

    /**
     * 描述:获取 post 请求的 byte[] 数组
     * @param request
     * @return
     * @throws IOException
     */
    public static byte[] getRequestPostBytes(HttpServletRequest request) throws IOException {
        int contentLength = request.getContentLength();
        if (contentLength < 0) {
            return null;
        }
        byte buffer[] = new byte[contentLength];
        for (int i = 0; i < contentLength;) {

            int readlen = request.getInputStream().read(buffer, i, contentLength - i);
            if (readlen == -1) {
                break;
            }
            i += readlen;
        }
        return buffer;
    }

    /**
     * 描述:获取 post 请求内容
     * @param request
     * @return
     * @throws IOException
     */
    public static String getRequestPostStr(HttpServletRequest request) throws IOException {
        byte buffer[] = getRequestPostBytes(request);
        if(buffer==null){
            return null;
        }
        
        String charEncoding = request.getCharacterEncoding();
        if (charEncoding == null) {
            charEncoding = "UTF-8";
        }
        return new String(buffer, charEncoding);
    }

    
    protected String getIpAddr() {  
        return WebUtil.getIpAddr(request);
    } 
    
    /**
     * ajax输出
     * 
     * @param content
     * @param type
     * @return
     */
    public APIRequest getAPIRequestByParamenters() {
        
        return WebUtil.getAPIRequestByParamenters(this.getRequest());
    }

    /**
     * 获得所有请求的参数
     * 
     * @param request
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public Map getRequestParamters() {
        // 获取所有的请求参数
        Map properties = this.getRequest().getParameterMap();
        // 返回值Map
        Map returnMap = new HashMap();
        Iterator entries = properties.entrySet().iterator();
        Map.Entry entry;
        String name = "";
        String value = "";
        // 读取map中的值
        while (entries.hasNext()) {
            entry = (Map.Entry) entries.next();
            name = (String) entry.getKey();
            Object valueObj = entry.getValue();
            if (null == valueObj) {
                value = " ";
                returnMap = JSON.parseObject(name);
            } else if (valueObj instanceof String[]) {
                String[] values = (String[]) valueObj;
                for (String value2 : values) {
                    value = value2 + ",";
                }
                value = value.substring(0, value.length() - 1);
            } else {
                value = valueObj.toString();
            }
            // 将读取到的值存入map中
            returnMap.put(name, value);
        }
        return returnMap;
    }

    /**
     * ajax输出
     * 
     * @param content
     * @param type
     * @return
     */
    public String ajax(String content, String type) {
        try {
            HttpServletResponse response = this.getResponse();
            response.setContentType(type + ";charset=UTF-8");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            PrintWriter out = response.getWriter();
            out.println(content);
            // out.flush();
            out.close();
        } catch (IOException e) {
            logger.error("basecontroller-ajax输入异常！", e);
        }
        return null;
    }

    /**
     * ajax,mime类型，text/html
     * 
     * @param xml
     * @return
     */
    @SuppressWarnings("unused")
    private String ajaxText(String text) {
        return this.ajax(text, "text/plain");
    }

    /**
     * ajax,mime类型，text/html
     * 
     * @param xml
     * @return
     */
    @SuppressWarnings("unused")
    private String ajaxHtml(String html) {
        return this.ajax(html, "text/html");
    }

    /**
     * ajax,mime类型，text/xml
     * 
     * @param xml
     * @return
     */
    @SuppressWarnings("unused")
    private String ajaxXml(String xml) {
        return this.ajax(xml, "text/xml");
    }

    /**
     * ajax,mime类型，text/javascript
     * 
     * @param xml
     * @return
     */
    private String ajaxJavaScript(String xml) {
        return this.ajax(xml, "text/javascript");
    }

    /**
     * 公共的处理和封装返回给前台ajax的数据
     * 
     * @param jo
     */
    public void renderJson4JsonObj(JSONObject jo) {
        String redata = null;
        redata = (jo == null ? "" : jo.toJSONString());
        // 如果jsonpCallback回调函数不为空，则说明是jsonp方式的请求，则封装格式
        // 否则为普通的ajax提交
        if (StringUtils.isNotEmpty(this.jsonpCallback)) {
            StringBuffer sb = new StringBuffer();
            redata = sb.append(this.jsonpCallback).append("(").append(redata).append(")").toString();
        }
        this.ajaxJavaScript(redata);
    }

    /**
     * 公共的处理和封装返回给前台ajax的数据
     * 
     * @param jo
     */
    public void renderJson4Str(String reval) {
        String redata = null;
        this.retJson = JSONObject.parseObject(reval);
        redata = (this.retJson == null ? new JSONObject().toString() : this.retJson.toString());
        // 如果jsonpCallback回调函数不为空，则说明是jsonp方式的请求，则封装格式
        // 否则为普通的ajax提交
        if (StringUtils.isNotEmpty(this.jsonpCallback)) {
            StringBuffer sb = new StringBuffer();
            redata = sb.append(this.jsonpCallback).append("(").append(redata).append(")").toString();
        }
        this.ajaxJavaScript(redata);
    }


    /**     
     * 获取当前用户 <br/> 
     * getCurrentUser <br/> 
     * @return userInfo
     */
    public UserInfo getCurrentUser(){
//		String accessToken = request.getHeader(AuthConstants.REQ_KEY_ACCESS_TOKEN);
//        if(ValidateUtils.isNull(accessToken)||"null".equals(accessToken)){
//            return null;
//        }
//		UserInfo userInfo=tokenLogic.getUserInfoByToken(accessToken);
		return null;
	}
    /**     
     * 清除当前用户token <br/> 
     * validateCurrentUser <br/> 
     * @return  APIResult <br/>   
     */
    public APIResult invalidCurrentUser(){
//    	String accessToken = request.getHeader(AuthConstants.REQ_KEY_ACCESS_TOKEN);
//		if(ValidateUtils.isNull(accessToken)||"null".equals(accessToken)){
//			return null;
//		}
//		//UserInfo userInfo=tokenLogic.getUserInfoByToken(accessToken);
//    	tokenLogic.deleteUserToken(accessToken, null);
		return new APIResult();
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public APIResult handleException(Exception ex, HttpServletRequest request) {

        logger.error("web api happened error!",ex);
         return WebExceptionHandler.handleException(ex, request);
    }
    
    
}
